﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Common;
using Taobao.Top.Api;
using Taobao.Top.Api.Request;
using Taobao.Top.Api.Domain;
using System.Net;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Xml;

public partial class top_crm_customlist : System.Web.UI.Page
{
    public string session = string.Empty;
    public string nick = string.Empty;
    public string typ = string.Empty;
    public string total = string.Empty;
    public string groupstr = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        string id = utils.NewRequest("id", utils.RequestType.QueryString);
        Common.Cookie cookie = new Common.Cookie();
        string taobaoNick = cookie.getCookie("nick");
        session = cookie.getCookie("top_sessiongroupbuy");
        string iscrm = cookie.getCookie("iscrm");
        Rijndael_ encode = new Rijndael_("tetesoft");
        nick = encode.Decrypt(taobaoNick);


        //过期判断
        if (string.IsNullOrEmpty(taobaoNick))
        {
            string msg = "尊敬的淘宝卖家，非常抱歉的告诉您，您还没有购买此服务或者登录信息已失效，如需继续使用请<a href='http://fuwu.taobao.com/serv/detail.htm?service_id=4545' target='_blank'>进入该服务</a>，谢谢！";
            Response.Redirect("buy.aspx?msg=" + HttpUtility.UrlEncode(msg));
            Response.End();
            return;
        }

        //过期判断
        if (!IsBuy(nick))
        {
            string msg = "尊敬的" + nick + "，非常抱歉的告诉您，只有VIP版本才能使用【客户关系营销】功能，如需继续使用请<a href='http://fuwu.taobao.com/ser/detail.htm?service_code=service-0-22904&frm=haoping' target='_blank'>购买高级会员服务</a>，谢谢！";
            Response.Redirect("buy.aspx?msg=" + HttpUtility.UrlEncode(msg));
            Response.End();
            return;
        }
        string groupguid = utils.NewRequest("groupguid", utils.RequestType.QueryString);

        if (!IsPostBack)
        {
            string sql = string.Empty;
            sql = "SELECT * FROM TCS_Group WHERE nick = '" + nick + "' AND isdel = 0";
            DataTable dt = utils.ExecuteDataTable(sql);

            string appkey = "12159997";
            string secret = "614e40bfdb96e9063031d1a9e56fbed5";

            IDictionary<string, string> param = new Dictionary<string, string>();
            param.Add("page_size", "100");
            param.Add("current_page", "1");

            string result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.crm.groups.get", session, param);
            Regex reg = new Regex(@"<group>([\s\S]*?)</group>", RegexOptions.IgnoreCase);
            MatchCollection match = reg.Matches(result);

            for (int i = 0; i < match.Count; i++)
            {
                string str = match[i].Groups[0].ToString();
                string groupid = GetValueByProperty(str, "group_id");
                string groupName = GetValueByProperty(str, "group_name");
                string groupCount = GetValueByProperty(str, "member_count");

                //如果数据库内有记录则显示
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    if (groupid == dt.Rows[j]["taobaoid"].ToString())
                    {
                        if (groupguid == groupid)
                        {
                            groupstr += "<option value='" + groupid + "' selected title='" + groupCount + "'>" + groupName + "</option>";
                        }
                        else
                        {
                            groupstr += "<option value='" + groupid + "' title='" + groupCount + "'>" + groupName + "</option>";
                        }
                    }
                }
            }
        }

        string page = utils.NewRequest("page", utils.RequestType.QueryString);

        BindData("", page, groupguid);
    }


    protected void Button2_Click(object sender, EventArgs e)
    {
        string groupguid = utils.NewRequest("groupguid", utils.RequestType.Form);
        if (groupguid != "")
        {
            Response.Redirect("customlist.aspx?groupguid=" + groupguid);
            return;
        }
        if (search.Text.Trim() == "")
        {
            Response.Redirect("customlist.aspx");
            return;
        }
        BindData(search.Text.Trim(), "1", "");
    }

    /// <summary>
    /// 判断该用户是否订购了该服务
    /// </summary>
    /// <param name="nick"></param>
    /// <returns></returns>
    private bool IsBuy(string nick)
    {
        string sql = "SELECT plus FROM TCS_ShopSession WHERE nick = '" + nick + "'";
        DataTable dt = utils.ExecuteDataTable(sql);
        if (dt.Rows.Count != 0)
        {
            string plus = dt.Rows[0][0].ToString();
            if (plus.IndexOf("crm") != -1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    public static string GetValueByProperty(string str, string prop)
    {
        Regex reg = new Regex(@"<" + prop + @">([^<]*)</" + prop + @">", RegexOptions.IgnoreCase);
        if (reg.IsMatch(str))
        {
            return reg.Match(str).Groups[1].ToString();
        }
        else
        {
            return "";
        }
    }

    private void BindData(string buynick, string page, string groupguid)
    {
        IDictionary<string, string> paramSheng = InitShengInfo();

        int pageNow = 1;
        if (page == "")
        {
            pageNow = 1;
        }
        else
        {
            pageNow = int.Parse(page);
        }

        string sql = "SELECT TOP 1 * FROM TCS_Customer WHERE 1 = 2";
        DataTable dt = utils.ExecuteDataTable(sql);

        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";

        IDictionary<string, string> param = new Dictionary<string, string>();
        param.Add("page_size", "12");
        param.Add("current_page", pageNow.ToString());
        param.Add("relation_source", "1");
        param.Add("order", "lastest_time");
        param.Add("sort", "desc");
        //param.Add("min_last_trade_time", DateTime.Now.AddYears(-4).ToString("yyyy-MM-dd HH:mm:ss"));
        //param.Add("max_last_trade_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

        if (buynick.Length != 0)
        {
            param.Add("buyer_nick", buynick);
        }
        if (groupguid.Length != 0)
        {
            if (groupguid.Length == 1)
            {
                param.Add("grade", groupguid);
            }
            else
            {
                param.Add("group_id", groupguid);
            }
        }

        string result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.crm.members.search", session, param);
        Regex reg = new Regex(@"<crm_member>([\s\S]*?)</crm_member>", RegexOptions.IgnoreCase);
        MatchCollection match = reg.Matches(result);

        //获取买家自定义分组
        param = new Dictionary<string, string>();
        param.Add("page_size", "100");
        param.Add("current_page", "1");
        string groupstr = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.crm.groups.get", session, param);

        for (int i = 0; i < match.Count; i++)
        {
            string str = match[i].Groups[0].ToString();
            DataRow row = dt.NewRow();

            string buyer_nick = GetValueByProperty(str, "buyer_nick");

            //获取买家用户等级
            param = new Dictionary<string, string>();
            param.Add("fields", "sex,buyer_credit.level,created,last_visit,birthday,email");
            param.Add("nick", buyer_nick);
            string nickresult = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.user.get", session, param);

            ////获取买家地址
            //param = new Dictionary<string, string>();
            //param.Add("fields", "receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_mobile");
            //param.Add("nick", nick);
            //param.Add("buyer_nick", buyer_nick);
            //param.Add("page_size", "1");
            //string traderesult = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.trades.sold.get", session, param);

            //绑定显示数据
            row["buynick"] = buyer_nick;
            row["buyerlevel"] = GetValueByProperty(nickresult, "level");
            row["sex"] = GetValueByProperty(nickresult, "sex");
            row["sheng"] = paramSheng[GetValueByProperty(str, "province")];
            row["shi"] = GetValueByProperty(str, "city");
            row["grade"] = GetValueByProperty(str, "grade");
            row["tradecount"] = GetValueByProperty(str, "trade_count");
            row["tradeamount"] = GetValueByProperty(str, "trade_amount");
            row["lastorderdate"] = GetValueByProperty(str, "last_trade_time");
            row["groupguid"] = ShowGroupStr(GetValueByProperty(str, "group_ids"), groupstr);

            dt.Rows.Add(row);
        }
        string pageUrl = "customlist.aspx?groupguid=" + groupguid;

        rptArticle.DataSource = dt;
        rptArticle.DataBind();

        int totalCount = int.Parse(GetValueByProperty(result, "total_result") == "" ? "0" : GetValueByProperty(result, "total_result"));
        total = totalCount.ToString();

        lbPage.Text = InitPageStr(totalCount, pageUrl);
    }

    private IDictionary<string, string> InitShengInfo()
    {
        IDictionary<string, string> param = new Dictionary<string, string>();
        param.Add("0", "其他");
        param.Add("1", "北京");
        param.Add("2", "天津");
        param.Add("3", "河北省");
        param.Add("4", "山西省");
        param.Add("5", "内蒙古自治区");
        param.Add("6", "辽宁省");
        param.Add("7", "吉林省");
        param.Add("8", "黑龙江省");
        param.Add("9", "上海");
        param.Add("10", "江苏省");
        param.Add("11", "浙江省");
        param.Add("12", "安徽省");
        param.Add("13", "福建省");
        param.Add("14", "江西省");
        param.Add("15", "山东省");
        param.Add("16", "河南省");
        param.Add("17", "湖北省");
        param.Add("18", "湖南省");
        param.Add("19", "广东省");
        param.Add("20", "广西壮族自治区");
        param.Add("21", "海南省");
        param.Add("22", "重庆");
        param.Add("23", "四川省");
        param.Add("24", "贵州省");
        param.Add("25", "云南省");
        param.Add("26", "西藏自治区");
        param.Add("27", "陕西省");
        param.Add("28", "甘肃省");
        param.Add("29", "青海省");
        param.Add("30", "宁夏回族自治区");
        param.Add("31", "新疆维吾尔自治区");
        param.Add("32", "台湾省");
        param.Add("33", "香港特别行政区");
        param.Add("34", "澳门特别行政区");
        param.Add("35", "海外");
        param.Add("36", "其他");

        return param;
    }

    /// <summary>
    /// 显示卖家自定义分组
    /// </summary>
    /// <param name="p"></param>
    /// <param name="groupstr"></param>
    /// <returns></returns>
    private string ShowGroupStr(string groupid, string groupstr)
    {
        string sql = string.Empty;
        sql = "SELECT * FROM TCS_Group WHERE nick = '" + nick + "' AND isdel = 0";
        DataTable dt = utils.ExecuteDataTable(sql);

        string str = string.Empty;
        int index = 0;
        Regex reg = new Regex(@"<group_name>([\s\S]*?)</group_name><group_id>([\s\S]*?)</group_id>", RegexOptions.IgnoreCase);
        MatchCollection match = reg.Matches(groupstr);

        for (int i = 0; i < match.Count; i++)
        {
            //如果数据库内有记录则显示
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                if (match[i].Groups[2].ToString() == dt.Rows[j]["taobaoid"].ToString())
                {
                    if (groupid.IndexOf(match[i].Groups[2].ToString()) != -1)
                    {
                        if (index == 0)
                        {
                            str += "【" + match[i].Groups[1].ToString() + "】";
                            index = 1;
                        }
                        else
                        {
                            str += "<br>" + "【" + match[i].Groups[1].ToString() + "】";
                        }
                    }
                }
            }
        }

        return str;
    }

    public static string getdateshort(string str)
    {
        if (str.Length == 0)
        {
            return "未设置";
        }
        else
        {
            string date = DateTime.Parse(str).ToString("yyyy-MM-dd");
            if (date == "1900-01-01")
            {
                return "未设置";
            }
            else
            {
                return date;
            }
        }
    }

    public static string getgrade(string grade)
    {
        string str = string.Empty;

        switch (grade)
        {
            case "0":
                str = "<span style='#eeeeee'>【未购买】</span>";
                break;
            case "1":
                str = "普通会员";
                break;
            case "2":
                str = "<span style='color:blue'>高级会员</span>";
                break;
            case "3":
                str = "<span style='color:green'>VIP会员</span>";
                break;
            case "4":
                str = "<span style='color:red'>至尊VIP会员</span>";
                break;
        }

        return str;
    }

    public static string getsex(string sex)
    {
        string str = string.Empty;

        switch (sex)
        {
            case "m":
                str = "男";
                break;
            case "f":
                str = "女";
                break;
            case "":
                str = "--";
                break;
        }

        return str;
    }


    public static string encode(string str)
    {
        return HttpUtility.UrlEncode(str);
    }


    private string InitPageStr(int total, string url)
    {
        //分页数据初始化
        string str = string.Empty;
        int pageCount = 12;
        int pageSize = 0;
        int pageNow = 1;
        string page = utils.NewRequest("page", utils.RequestType.QueryString);
        if (page == "")
        {
            pageNow = 1;
        }
        else
        {
            pageNow = int.Parse(page);
        }

        //取总分页数
        if (total % pageCount == 0)
        {
            pageSize = total / pageCount;
        }
        else
        {
            pageSize = total / pageCount + 1;
        }

        //如果总页面大于20，则最大页面差不超过20
        int start = 1;
        int end = 20;

        if (pageSize < end)
        {
            end = pageSize;
        }
        else
        {
            if (pageNow > 15)
            {
                start = pageNow - 10;

                if (pageNow < (pageSize - 10))
                {
                    end = pageNow + 10;
                }
                else
                {
                    end = pageSize;
                }
            }
        }

        for (int i = start; i <= end; i++)
        {
            if (i.ToString() == pageNow.ToString())
            {
                str += i.ToString() + " ";
            }
            else
            {
                str += "<a href='" + url + "&page=" + i.ToString() + "'>[" + i.ToString() + "]</a> ";
            }
        }

        return str;
    }


    #region TOP API
    /// <summary> 
    /// 给TOP请求签名 API v2.0 
    /// </summary> 
    /// <param name="parameters">所有字符型的TOP请求参数</param> 
    /// <param name="secret">签名密钥</param> 
    /// <returns>签名</returns> 
    protected static string CreateSign(IDictionary<string, string> parameters, string secret)
    {
        parameters.Remove("sign");
        IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
        IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
        StringBuilder query = new StringBuilder(secret);
        while (dem.MoveNext())
        {
            string key = dem.Current.Key;
            string value = dem.Current.Value;
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
            {
                query.Append(key).Append(value);
            }
        }
        query.Append(secret);
        MD5 md5 = MD5.Create();
        byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < bytes.Length; i++)
        {
            string hex = bytes[i].ToString("X");
            if (hex.Length == 1)
            {
                result.Append("0");
            }
            result.Append(hex);
        }
        return result.ToString();
    }
    /// <summary> 
    /// 组装普通文本请求参数。 
    /// </summary> 
    /// <param name="parameters">Key-Value形式请求参数字典</param> 
    /// <returns>URL编码后的请求数据</returns> 
    protected static string PostData(IDictionary<string, string> parameters)
    {
        StringBuilder postData = new StringBuilder();
        bool hasParam = false;
        IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
        while (dem.MoveNext())
        {
            string name = dem.Current.Key;
            string value = dem.Current.Value;
            // 忽略参数名或参数值为空的参数 
            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
            {
                if (hasParam)
                {
                    postData.Append("&");
                }
                postData.Append(name);
                postData.Append("=");
                postData.Append(Uri.EscapeDataString(value));
                hasParam = true;
            }
        }
        return postData.ToString();
    }
    /// <summary> 
    /// TOP API POST 请求 
    /// </summary> 
    /// <param name="url">请求容器URL</param> 
    /// <param name="appkey">AppKey</param> 
    /// <param name="appSecret">AppSecret</param> 
    /// <param name="method">API接口方法名</param> 
    /// <param name="session">调用私有的sessionkey</param> 
    /// <param name="param">请求参数</param> 
    /// <returns>返回字符串</returns> 
    public static string Post(string url, string appkey, string appSecret, string method, string session,
    IDictionary<string, string> param)
    {
        #region -----API系统参数----
        param.Add("app_key", appkey);
        param.Add("method", method);
        param.Add("session", session);
        param.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        param.Add("format", "xml");
        param.Add("v", "2.0");
        param.Add("sign_method", "md5");
        param.Add("sign", CreateSign(param, appSecret));
        #endregion
        string result = string.Empty;
        #region ---- 完成 HTTP POST 请求----
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "POST";
        req.KeepAlive = true;
        req.Timeout = 300000;
        req.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
        byte[] postData = Encoding.UTF8.GetBytes(PostData(param));
        Stream reqStream = req.GetRequestStream();
        reqStream.Write(postData, 0, postData.Length);
        reqStream.Close();
        HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
        Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
        Stream stream = null;
        StreamReader reader = null;
        stream = rsp.GetResponseStream();
        reader = new StreamReader(stream, encoding);
        result = reader.ReadToEnd();
        if (reader != null) reader.Close();
        if (stream != null) stream.Close();
        if (rsp != null) rsp.Close();
        #endregion
        return Regex.Replace(result, @"[\x00-\x08\x0b-\x0c\x0e-\x1f]", "");
    }
    #endregion
}